package coreClassLibrary;

public class ExceptionHandlingDemo {
    public static void main(String[] args) {
        // 1. try-catch 基本异常处理
        try {
            int result = divide(10, 0);
            System.out.println("结果是: " + result);
        } catch (ArithmeticException e) {
            System.out.println("捕获算术异常: " + e.getMessage());
        }

        // 2. 多重catch处理不同类型的异常
        try {
            String[] arr = {"Hello"};
            System.out.println(arr[1]); // 数组越界
            Integer.parseInt("abc"); // 数字格式异常
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("数组越界异常: " + e.getMessage());
        } catch (NumberFormatException e) {
            System.out.println("数字格式异常: " + e.getMessage());
        }

        // 3. try-catch-finally 示例
        try {
            checkAge(-5);
        } catch (CustomAgeException e) {
            System.out.println("年龄验证异常: " + e.getMessage());
        } finally {
            System.out.println("finally 块总是会执行");
        }

        // 4. throws 声明异常
        try {
            readFile("nonexistent.txt");
        } catch (Exception e) {
            System.out.println("文件操作异常: " + e.getMessage());
        }
    }

    // 演示可能抛出异常的方法
    public static int divide(int a, int b) {
        return a / b;
    }

    // 自定义异常类
    static class CustomAgeException extends Exception {
        public CustomAgeException(String message) {
            super(message);
        }
    }

    // 使用throws声明异常的方法
    public static void checkAge(int age) throws CustomAgeException {
        if (age < 0) {
            throw new CustomAgeException("年龄不能为负数");
        }
        System.out.println("年龄验证通过");
    }

    // 使用throws声明检查异常
    public static void readFile(String filename) throws Exception {
        throw new Exception("文件不存在");
    }
} 
